package com.mrzhou.system.controller;

import com.mrzhou.common.constant.RoleConstant;
import com.mrzhou.system.entity.Menu;
import com.mrzhou.common.enums.system.MenuType;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.constants.StringSymbol;
import com.mrzhou.core.tool.utils.BeanUtil;
import com.mrzhou.core.tool.utils.Func;
import com.mrzhou.mybatis.support.Condition;
import com.mrzhou.mybatis.support.ParentTree;
import com.mrzhou.system.req.PageMenuReq;
import com.mrzhou.system.service.IMenuService;
import com.mrzhou.system.vo.MenuVO;
import com.mrzhou.web.secure.annotation.BeforeAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单接口
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单接口")
@BeforeAuth(RoleConstant.ADMINISTRATOR)
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @PostMapping("/list")
    @ApiOperation(value = "列表", notes = "传入menu")
    public R<List<MenuVO>> list(@RequestBody PageMenuReq req) {
        List<Menu> menuList;
        if (Func.isNotEmpty(req.getParentId())) {
            menuList = menuService.treeMenuListByParentId(req.getParentId());
        } else {
            menuList = menuService.list(Condition.getQueryWrapper(req, Menu.class));
        }

        List<MenuVO> menuVOList = menuList.stream().map(menu -> BeanUtil.copy(menu, MenuVO.class)).collect(Collectors.toList());
        return R.data(ParentTree.convertListToTree(menuVOList));
    }

    @PostMapping("submit")
    @ApiOperation("修改或更新")
    public R<String> submit(@Valid @RequestBody Menu menu) {
        // 补充部分默认数据
        if (MenuType.F.equals(menu.getMenuType())) {
            menu.setPath(StringSymbol.WELL);
            menu.setIcon(StringSymbol.WELL);
            menu.setRemark(menu.getMenuName() + MenuType.F.des());
        } else if (MenuType.M.equals(menu.getMenuType())) {
            menu.setRemark(menu.getMenuName() + MenuType.M.des());
        } else {
            menu.setRemark(menu.getMenuName() + MenuType.C.des());
        }
        return R.status(menuService.submit(menu));
    }

}
